import ujson
import sys
sys.path.append('../../')
# from models.audi.cars_audi import CarsAudi
from models.audi.audi_parts import AudiParts
from models.audi.audi_193 import CarsPartNumNew, CarsStructureCollectionNew
from models.audi.audi_date import AudiDateBanzhou,AudiDate

def audi_do_filter_extra_info(partExtraInfo, **kwargs):
    anddate = []
    andcolordate = []
    andyear = []
    ordate = []
    orcolordate = []
    oryear = []
    partExtraJsonAndList = partExtraInfo.split("&&")
    for partAndData in partExtraJsonAndList[:-1]:
        extraAnd = ujson.loads(partAndData)
        extraAndDate = extraAnd.get('date') or []
        extraAndcolorDate = extraAnd.get('colorDate') or []
        extraAndYear = extraAnd.get('year') or []
        anddate += extraAndDate
        andcolordate += extraAndcolorDate
        andyear += extraAndYear
    anddate = '&'.join(anddate)
    andcolordate = '&'.join(andcolordate)
    andyear = '&'.join(andyear)

    extra_info = partExtraJsonAndList[-1]
    partExtraJsonOrList = extra_info.split('|')
    for partOrDate in partExtraJsonOrList:
        if partOrDate == '':
            partOrDate = '{}'
        extraOr = ujson.loads(partOrDate)
        extraOrDate = extraOr.get('date') or []
        extraOrcolorDate = extraOr.get('colorDate') or []
        extraOrYear = extraOr.get('year') or []
        ordate += extraOrDate
        orcolordate += extraOrcolorDate
        oryear += extraOrYear
    ordate = '|'.join(ordate)
    orcolordate = '|'.join(orcolordate)
    oryear = '|'.join(oryear)

    date = anddate.strip()+ ('&' if anddate.strip() and ordate.strip() else '') +ordate.strip()
    colorDate = andcolordate.strip() + ('&' if andcolordate.strip() and orcolordate.strip() else '') +orcolordate.strip()
    year = andyear.strip() + ('&' if andyear.strip() and oryear.strip() else '') + oryear.strip()
    return date if date else None, colorDate if colorDate else None, year if year else None

# def cleanDate():
    # cars_audi = AudiParts.select().where(AudiParts.standard_label == '半轴')
    # for a in cars_audi:
    #     insert_data = []
    #     parts = CarsPartNumNew.select().where(CarsPartNumNew.pid == a.pid)
    #     for part in parts:
#     extra_info = part.extra_info
#     date, colorDate, year = audi_do_filter_extra_info(extra_info)
#     print(date)
#     print(colorDate)
#     print(year)
#     structure = CarsStructureCollectionNew.get_or_none(CarsStructureCollectionNew.cid == part.cid, CarsStructureCollectionNew.mid == part.mid)
#     if structure:
#         sdate, scolordate, syear = audi_do_filter_extra_info(structure.extra_info)
#     else:
#         sdate, scolordate, syear = '', '', ''
#     data={ 'pid':part.pid,
#         'cid':part.cid,
#         'mid':part.mid,
#         'bread_code':'audi',
#         'date':date,
#         'colordate':colorDate,
#         'year':year,
#         'sdate':sdate,
#         'scolordate':scolordate,
#         'syear':syear
#     }
#
#     insert_data.append(data)
#
# AudiDateBanzhou.insert_many(insert_data).execute()

def mergeDate(date):
    if date:
        leftAnd = []
        rightAnd = []
        if date.endswith('&'):
            date = date[:-1]
        dataAndList = date.split('|')
        for andDate in dataAndList:
            andDate = andDate.strip()
            if andDate.endswith('-'):
                leftAnd.append(andDate[0:4])
            elif andDate.startswith('-'):
                rightAnd.append(andDate[1:5])
            elif '-' in andDate and (not andDate.endswith('-')) and (not andDate.startswith('-')):
                leftAnd.append(andDate[0:4])
                rightAnd.append(('-'.join(andDate.split('-')[1:]))[0:4])
        return min(leftAnd) if leftAnd else None, max(rightAnd) if rightAnd else None
    else:
        return None, None

if __name__ == '__main__':
    # audiDatebanzhou = AudiDateBanzhou().select()
    # insert_data = []
    # for dateInfo in audiDatebanzhou:
    #     date = dateInfo.date
    #     date = date.strip()
    #     dateLeft, dateRight = mergeDate(date)
    #
    #     colordate = dateInfo.colordate
    #     colordate = colordate.strip()
    #     colordateLeft, colordateRight = mergeDate(colordate)
    #
    #     year = dateInfo.year
    #     year = year.strip()
    #     yearLeft, yearRight = mergeDate(year)
    #     print(dateLeft)
    #     print(colordateLeft)
    #     print(yearLeft)
    #     leftList = [dateLeft, colordateLeft, yearLeft]
    #     rightList = [dateRight, colordateRight, yearRight]
    #     mdateLeft = max(leftList) if leftList else ''
    #     mdateRight = min(rightList) if rightList else ''
    #
    #     merge_date = mdateLeft + '-' + mdateRight
    #
    #     sdate = dateInfo.sdate
    #     sdate = sdate.strip()
    #     sdateLeft, sdateRight = mergeDate(sdate)
    #
    #     scolordate = dateInfo.scolordate
    #     scolordate = scolordate.strip()
    #     scolordateLeft, scolordateRight = mergeDate(scolordate)
    #
    #     syear = dateInfo.syear
    #     syear = syear.strip()
    #     syearLeft, syearRight = mergeDate(syear)
    #
    #     sleftList = [sdateLeft, scolordateLeft, syearLeft]
    #     srightList = [sdateRight, scolordateRight, syearRight]
    #     msdateLeft = max(sleftList) if sleftList else ''
    #     msdateRight = min(srightList) if srightList else ''
    #
    #     merge_sdate = msdateLeft + '-' + msdateRight
    #
    #     date = {'merge_date': merge_date, 'merge_sdate': merge_sdate}
    #     insert_data.append(date)
    # AudiDateBanzhou.update(insert_data).execute()

    extra_info = '{"PR": {"missing_sa": ["TV2"], "params": {"GMO": {"TV2": ["-20151231", "20160101-"]}, "MOT": {"D2D": ["-20101231", "20110101-20111231", "20120101-20151231", "20160101-"]}}, "saDict": {"GSP": ["G0Z"], "GMO": ["TV2"], "MOT": ["D2D"]}}, "missing_sa": ["TV2"], "engs": [], "DE_M": [], "G": [], "F": [], "colorDate": [], "NA": [], "CG": [], "NB": [], "M": [], "params": {"GMO": {"TV2": ["-20151231", "20160101-"]}, "MOT": {"D2D": ["-20101231", "20110101-20111231", "20120101-20151231", "20160101-"]}}, "C1": [], "year": [], "date": ["20090727-20140602"], "CR": [], "sa": {"GSP": ["G0Z"], "GMO": ["TV2"], "MOT": ["D2D"]}, "trans": [], "C2": []}'

    # print(audi_do_filter_extra_info(extra_info))

    date, colorDate, year = audi_do_filter_extra_info(extra_info)
    dateLeft, dateRight = mergeDate(date)
    leftList = []
    if dateLeft:
        leftList.append(dateLeft)

    rightList = []
    if dateRight:
        rightList.append(dateRight)
    mdateLeft = max(leftList) if leftList else ''
    mdateRight = min(rightList) if rightList else ''
    print(mdateLeft)
    print(mdateRight)
    # if mdateLeft or mdateRight:
    #     merge_date = mdateLeft + '-'  + mdateRight
    # elif mdateLeft:
    #     merge_date = mdateLeft + '-'
    # elif mdateRight:
    #     merge_date = '-' + mdateRight
    # else:
    #     merge_date = ''
    merge_date = mdateLeft + ('-' if mdateLeft or mdateRight else '') + mdateRight
    print(merge_date)

